package com.piggy.logi.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.piggy.common.core.constant.UserConstants;
import com.piggy.common.core.domain.R;
import com.piggy.common.core.utils.StringUtils;
import com.piggy.common.core.web.controller.BaseController;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.common.log.annotation.LogiLog;
import com.piggy.common.log.enums.BusinessType;
import com.piggy.common.satoken.annotation.Inner;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.logi.sys.api.domain.LogiSysDept;
import com.piggy.logi.sys.api.vo.LogiSysDeptExtVo;
import com.piggy.logi.sys.api.bo.LogiSysDeptExtCusEditBo;
import com.piggy.logi.sys.service.ILogiSysDeptExtService;
import com.piggy.logi.sys.service.ILogiSysDeptService;
import com.piggy.logi.sys.vo.LogiTreeSelect;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 部门信息
 *
 * @author shark
 */
@RestController
@RequestMapping("/logi/dept")
public class LogiSysDeptController extends BaseController {
    @Resource
    private ILogiSysDeptService deptService;

    @Resource
    private ILogiSysDeptExtService deptExtService;

    /**
     * 获取部门列表
     */
    //@SaCheckPermission("system:dept:list")
    @PostMapping("/list")
    @ResponseBody
    public R<List<LogiSysDeptExtVo>> list(@RequestBody LogiSysDept dept) {
        List<LogiSysDeptExtVo> depts = deptService.selectDeptList(dept);
        return R.ok(depts);
    }

    /**
     * 获取部门列表
     */
    //@SaCheckPermission("system:dept:list")
    @Inner
    @PostMapping("/rootList")
    @ResponseBody
    public TableDataInfo<LogiSysDeptExtVo> rootList(@RequestBody LogiSysDept dept) {
        return deptService.selectRootDeptList(dept);
    }

    /**
     * 查询部门列表（排除节点）
     */
    //@SaCheckPermission("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public R excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<LogiSysDeptExtVo> depts = deptService.selectDeptList(new LogiSysDept());
        Iterator<LogiSysDeptExtVo> it = depts.iterator();
        while (it.hasNext()) {
            LogiSysDeptExtVo d = (LogiSysDeptExtVo) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return R.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    //@SaCheckPermission("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public R<LogiSysDeptExtVo> getInfo(@PathVariable Long deptId) {
        return R.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public R treeselect(LogiSysDept dept) {
        List<LogiSysDeptExtVo> depts = deptService.selectDeptList(dept);
        return R.ok(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public R roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<LogiSysDeptExtVo> depts = deptService.selectDeptList(new LogiSysDept());
        Map<String, Object> ajax = new HashMap<>(2);
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return R.ok(ajax);
    }

    /**
     * 获取组织类型id
     */
    @Inner
    @GetMapping(value = "/getOrgDeptId/{deptId}")
    public Long getOrgDeptId(@PathVariable("deptId") Long deptId) {
        return deptService.getOrgDeptId(deptId);
    }

    /**
     * 新增部门
     */
    //@SaCheckPermission("system:dept:add")
    @LogiLog(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody LogiSysDeptExtCusEditBo dept1) {
        LogiSysDept dept = BeanUtil.toBean(dept1, LogiSysDept.class);
        dept.setMainDeptId(SecurityUtils.getDeptId());
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return R.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getPhone());
        dept.setParentId(SecurityUtils.getDeptId());
        //return toAjax(deptService.insertDept(dept));
        LogiSysDeptExtVo vo = deptExtService.insertByAddBo(dept1);
        if (ObjectUtil.isNotEmpty(vo)) {
            return R.ok();
        }
        return R.fail();

    }

    /**
     * 修改部门
     */
    //@SaCheckPermission("system:dept:edit")
    @LogiLog(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody LogiSysDeptExtCusEditBo dept1) {
        LogiSysDept dept = BeanUtil.toBean(dept1, LogiSysDept.class);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return R.fail("组织名称或组织编码已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return R.fail("上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return R.fail("该部门包含未停用的子部门！");
        }
        dept1.setUpdateBy(SecurityUtils.getPhone());
        dept1.setUpdateTime(new Date());
        //return toAjax(deptService.updateDept(dept));
        LogiSysDeptExtVo vo = deptExtService.updateByEditBo(dept1);
        if (ObjectUtil.isNotEmpty(vo)) {
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 删除部门
     */
    //@SaCheckPermission("system:dept:remove")
    @LogiLog(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public R remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return R.fail("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return R.fail("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 删除部门
     */
    //@SaCheckPermission("system:dept:remove")
    @Inner
    @LogiLog(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/root/{deptId}")
    public R removeRoot(@PathVariable("deptId") Long deptId) {
/*
        if (deptService.hasChildByDeptId(deptId)) {
            return R.fail("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return R.fail("部门存在用户,不允许删除");
        }
*/
        return toAjax(deptService.deleteDeptById(deptId));
    }

    @Inner
    @PostMapping("/queryDeptAll")
    public R<List<LogiSysDeptExtVo>> queryDeptAll() {
        return R.ok(deptService.queryDeptAll());
    }


    @Inner
    @GetMapping("/getById")
    public R<LogiSysDeptExtVo> getById(@RequestParam Long deptId){
        return R.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @Inner
    @PostMapping(value = "/saveSysDept")
    public R<LogiSysDept> saveSysDept(@RequestBody LogiSysDept logiSysDept) {
        deptService.saveOrUpdate(logiSysDept);
        return R.ok(logiSysDept);
    }

    /**
     * 获取部门树列表
     */
    //("system:user:list")
    //@SaCheckPermission("system:dept:list")
    @GetMapping("/deptTree")
    public R<List<LogiTreeSelect>> deptTree(LogiSysDept dept) {
        List<LogiSysDeptExtVo> depts = deptService.selectDeptList(dept);
        return R.ok(deptService.buildDeptTreeSelect(depts));
    }

    @ApiOperation("根据经纬度获取网点信息")
    @GetMapping("/geo")
    public List<LogiSysDeptExtVo> geo(@RequestParam("lng") BigDecimal lng, @RequestParam("lat") BigDecimal lat) {
        return deptService.selectGeoDeptList(lng, lat);
    }

    /**
     * 新增部门
     */
    //@SaCheckPermission("system:dept:add")
    @Inner
    @LogiLog(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/bossAdd")
    public R<LogiSysDeptExtVo> bossAdd(@Validated @RequestBody LogiSysDeptExtCusEditBo dept1) {
        LogiSysDept dept = BeanUtil.toBean(dept1, LogiSysDept.class);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return R.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept1.setCreateBy("admin");
        dept1.setCreateTime(new Date());
        //return toAjax(deptService.insertDept(dept));
        dept1.setParentId(0L);
        dept1.setAncestors(String.valueOf(dept1.getParentId()));
        LogiSysDeptExtVo vo = deptExtService.insertByAddBo(dept1);
        if (ObjectUtil.isNotEmpty(vo)) {
            return R.ok(vo);
        }
        return R.fail();

    }

    /**
     * 修改部门
     */
    //@SaCheckPermission("system:dept:edit")
    @Inner
    @LogiLog(title = "部门管理", businessType = BusinessType.UPDATE)
    @PostMapping("/bossEdit")
    public R<LogiSysDeptExtVo> bossEdit(@Validated @RequestBody LogiSysDeptExtCusEditBo dept1) {
        LogiSysDept dept = BeanUtil.toBean(dept1, LogiSysDept.class);
        if (StrUtil.isNotBlank(dept.getDeptName())) {
            if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
                return R.fail("组织名称或组织编码已存在");
            } else if (dept.getParentId().equals(dept.getDeptId())) {
                return R.fail("上级部门不能是自己");
            } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                    && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
                return R.fail("该部门包含未停用的子部门！");
            }
        }

        dept1.setUpdateBy("admin");
        dept1.setUpdateTime(new Date());
        //return toAjax(deptService.updateDept(dept));
        LogiSysDeptExtVo vo = deptExtService.updateByEditBo(dept1);
        if (ObjectUtil.isNotEmpty(vo)) {
            return R.ok(vo);
        }
        return R.fail();
    }
}
